package app.android.database;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.content.ContentValues;
import android.content.Context;
import android.content.res.Resources;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
import android.util.Log;
import app.android.model.Food;
import app.android.model.TypeFood;
import app.android.sotaynauan.R;

public class MyDatabaseHelper extends SQLiteOpenHelper {
	private static final String CREATE_TABLE_FOOD = "create table " +
			Constants.FOOD_TABLE_NAME+" ("+ 
			Constants.KEY_ID+" integer primary key autoincrement, "+ 
			Constants.FOOD_NAME+" text not null, "+ 
			Constants.FOOD_TYPEID+" integer not null, "+
			Constants.FOOD_IMAGE_PATH+" text null, "+
			Constants.FOOD_DESCRIPTION+" text null, "+			
			Constants.FOOD_FAVOURITE+" integer null);";		
	
	private static final String CREATE_TABLE_TYPE = "create table " +
			Constants.TYPE_TABLE_NAME+" ("+ 
			Constants.KEY_ID+" integer primary key autoincrement, "+ 
			Constants.TYPE_NAME+" text not null, "+							
			Constants.TYPE_DESCRIPTION+" text null);";
	
	private static final String CREATE_TABLE_HISTORY = "create table " +
			Constants.HIS_TABLE_NAME+" ("+ 
//			Constants.KEY_ID+" integer primary key autoincrement, "+ 
			Constants.HIS_FOOD_ID+" integer primary key, "+							
			Constants.HIS_TIME+" date not null);";

	private final Context mContext;
	public static final String TAG = "SoTayNauAnDatabase";
	
	public MyDatabaseHelper(Context context, String name, CursorFactory factory, int version) {
		super(context, name, factory, version);
		// TODO Auto-generated constructor stub
		mContext = context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		Log.v("MyDB helper on create","Creating all table");
		try {
			db.execSQL(CREATE_TABLE_FOOD);			
			db.execSQL(CREATE_TABLE_TYPE);
			db.execSQL(CREATE_TABLE_HISTORY);
			loadDictionary(db);
		}catch (SQLiteException e) {
			Log.v("Create table exception",e.getMessage());
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.w("TaskDBAdapter", "Upgrading from version "+oldVersion 
				+" to "+newVersion 
				+", which will destroy all old data");
		db.execSQL("drop table if exists "+Constants.FOOD_TABLE_NAME);
		db.execSQL("drop table if exists "+Constants.TYPE_TABLE_NAME);
		db.execSQL("drop table if exists "+Constants.HIS_TABLE_NAME);	
		
		onCreate(db);
	}
	
	private void loadDictionary(final SQLiteDatabase db) {
        new Thread(new Runnable() {
            public void run() {
                try {
                	loadData(db);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }
	
	private void loadData(SQLiteDatabase db) throws IOException {		
       insertDefaultTypes(db);
       insertDefaultFoods(db);
       this.close();
    }
	
	private void insertDefaultFoods (SQLiteDatabase db) throws IOException{
		Resources resources = mContext.getResources();
        InputStream inputStream = resources.openRawResource(R.raw.initialdata);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

        try {        	
            String line;
            while ((line = reader.readLine()) != null) {
                String[] strings = TextUtils.split(line, "\t");
                if (strings.length < 4) continue;
                Food f = new Food(strings[1].trim(), Integer.parseInt(strings[2].trim()), strings[0].trim(), strings[3].trim(), 0);
                ContentValues initialValues = new ContentValues();
                initialValues.put(Constants.FOOD_NAME, f.getFoodName());
                initialValues.put(Constants.FOOD_TYPEID, f.getTypeID());
                initialValues.put(Constants.FOOD_IMAGE_PATH, f.getImagePath());
                initialValues.put(Constants.FOOD_DESCRIPTION, f.getDescription());                
                initialValues.put(Constants.FOOD_FAVOURITE, false);                    
                long id = db.insert(Constants.FOOD_TABLE_NAME, null, initialValues);
                
	            if (id < 0) {
	                Log.e(TAG, "unable to add food: " + strings[0].trim());
	            }
            }
        } finally {
            reader.close();
           
        }
	}
	
	private void insertDefaultTypes (SQLiteDatabase db) throws IOException {
		Resources resources = mContext.getResources();
        InputStream inputStream = resources.openRawResource(R.raw.initialdata_2);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

        try {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] strings = TextUtils.split(line, "\t");
                if (strings.length < 2) continue;
                TypeFood type = new TypeFood(strings[0].trim(), strings[0].trim());
                ContentValues initialValues = new ContentValues();
                initialValues.put(Constants.TYPE_NAME, type.getTypeName());
                initialValues.put(Constants.TYPE_DESCRIPTION, type.getDescription());                 
                long id = db.insert(Constants.TYPE_TABLE_NAME, null, initialValues);
                
	            if (id < 0) {
	                Log.e(TAG, "unable to add type food: " + strings[0].trim());
	            }
            }
        } finally {
            reader.close();
         
        }
	}
	

}
